package pt.compflow.activity.workflow;

import pt.compflow.flowontology.model.Event;
import pt.compflow.flowontology.model.EventInterface;
import pt.compflow.flowontology.model.FLOWO;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.flowontology.model.Workflow;
import pt.compflow.interfaces.IOInterface;
import pt.compflow.storage.TripleStoreConnection;
import pt.compflow.tools.OntModelHelper;

import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.StmtIterator;

/**
 *	This command unsubscribes a specific event or event-type from an EventInterface
 *
 */
public class WorkflowControllerUnsubscribeEventCommand implements Runnable {

	//private static final Logger LOG = LoggerFactory.getLogger(WorkflowControllerUnsubscribeEvent.class);

	protected WorkflowControllerImpl controller;
	protected String eventUri;
	protected String jobUri;
	
	public WorkflowControllerUnsubscribeEventCommand(WorkflowControllerImpl controller, String jobUri, String eventUri) {
		this.controller = controller;
		this.eventUri = eventUri;
		this.jobUri = jobUri;
	}

	@Override
	public void run() {
		
		TripleStoreConnection store = controller.getContext().getStoreConnection();
		store.openStore();
		
		FlowOntologyModel engineModel = store.connectModel();
		FlowOntologyModel jobModel = store.connectNamedModel(jobUri);
		
		Event ev = jobModel.getEventWithURI(eventUri);
		Workflow wf = ev.getActivityOfWorkflow();
						
		OntModelHelper ontModelHelper = controller.getContext().getOntModelHelperManager().get(store, jobUri, wf.getRootWorkflow().getLocalName());
			
		StmtIterator evInterfaceIt = ev.listProperties(FLOWO.deliveredThrough);
		Resource actClass = ontModelHelper.getDirectLeafType(ev, FLOWO.Event.getURI());
		
		while(evInterfaceIt.hasNext()) {
			EventInterface evInterface = engineModel.getEventInterfaceWithURI(evInterfaceIt.next().getObject().asResource().getURI());
			Resource evInterfaceClass = ontModelHelper.getDirectLeafType(evInterface, FLOWO.EventInterface.getURI());
			IOInterface interfaze = controller.getContext().getEventInterfaceManager().get(evInterface, evInterfaceClass, ontModelHelper.getOntModel(), controller.getContext(), store);
			((pt.compflow.interfaces.event.EventInterface)interfaze).unsubscribe(controller.getContext(), store, ontModelHelper, jobModel, engineModel, jobUri, actClass, ev);
		}
		
		store.closeStore();
	}
	
}
